//
//  SearchViewController.m
//  花花时尚
//
//  Created by 霍文轩 on 15/9/2.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

#import "SearchDatabaseViewController.h"
#import "NightMode.h"
#import "CollectNewsDatabase.h"
#import "CollectNewsModel.h"
#import "NewsTableCell.h"
#import "FashionNewsModel.h"
#import "FashionDetailView.h"
#import "ArticleModel.h"
#import "SinglePullLayout.h"
#import "DailyCollectionCell.h"
#import "DailyDetailViewController.h"

#import "CollectProgramaDatabase.h"
#import "CollectProgramaModel.h"

@interface SearchDatabaseViewController () <UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic,retain) UISegmentedControl * segment;
@property (nonatomic,retain) UISearchBar * searchBar;
@property (nonatomic,retain) NSMutableArray * tableArray;
@property (nonatomic,retain) NSMutableArray * collectionArray;
@property (nonatomic,copy) NSString * searchText;
@property (nonatomic,retain) UICollectionView * collection;
@property (nonatomic,retain) UITableView * table;
@end

@implementation SearchDatabaseViewController
#define kCellHeight 215
- (void)dealloc
{
    [_table release];
    [_collection release];
    [_collectionArray release];
    [_tableArray release];
    [_segment release];
    [_searchBar release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.searchText = @"";
        self.tableArray = [NSMutableArray array];
        self.collectionArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_light" ofType:@"png"]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];
    
    NSArray * segArr = @[@"资讯",@"栏目"];
    self.segment = [[UISegmentedControl alloc] initWithItems:segArr];
    _segment.selectedSegmentIndex = 0;
    _segment.frame = CGRectMake(0, 0, 140, 30);
    _segment.center = CGPointMake(self.view.frame.size.width/2, 34);
    _segment.tintColor = [NightMode nightModeON]?[UIColor whiteColor]:[UIColor lightGrayColor];
    [_segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    UIBarButtonItem * buttonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(dismissView)]; // 返回按钮
    buttonItem.tintColor =[NightMode nightModeON]?[UIColor whiteColor]:[UIColor blackColor];
    
    // 自己创建一个navitionBar
    UINavigationBar * bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    bar.barStyle = [NightMode nightModeON]?UIBarStyleBlack:UIBarStyleDefault;
    UINavigationItem * item = [[UINavigationItem alloc] init];
    item.rightBarButtonItem = buttonItem;
    item.titleView = _segment; // 把item的titleView设置为
    [bar setItems:@[item]]; // 把bar的item设置为item
    
    [self.view addSubview:bar];
    [bar release];
    [item release];
    [buttonItem release];
    [_segment release];

    [self createSearchBar];
    [self createTable];
    [self createCollection];
}
// 界面返回
-(void)dismissView{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - setment的事件
-(void)segmentAction:(UISegmentedControl *)segment{
    _searchBar.text = @""; // 每次切换segment，都让text为空
}
#pragma  mark - 创建searchBar
-(void)createSearchBar{
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 50)];
    [_searchBar becomeFirstResponder];
    _searchBar.delegate = self;
    _searchBar.barTintColor = [UIColor purpleColor]; // 修改颜色
    _searchBar.placeholder = @"请输入时尚关键词";
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    [self.view addSubview:_searchBar];
    [_searchBar release];
}
#pragma mark - searchBarDelegate
// 当文字改变时调用，每次改变都查询结果，如果查询到，就创建collectionView或者tableView
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    if([searchText isEqualToString:@""]){ // 如果为空，清空数组，刷新数据，直接返回
        [_collectionArray removeAllObjects];
        [_collection reloadData];
        [_tableArray removeAllObjects];
        [_table reloadData];
        return;
    }
    
    self.searchText = searchText;
    [_collectionArray removeAllObjects]; // 每次改变都删除所有的model
    [_tableArray removeAllObjects];
    
    if(_segment.selectedSegmentIndex == 0){
        CollectNewsModel * collectModel = [CollectNewsDatabase selectWithTitle:searchText];
        if(collectModel != nil){
            // model转化
            FashionNewsModel * model = [[FashionNewsModel alloc] init];
            model.contentid = collectModel.c_contentid;
            model.title = collectModel.c_title;
            model.thumb = collectModel.c_thumb;
            model.cat_logo = collectModel.c_cat_logo;
            
            [self.tableArray addObject:model];
            [model release];
            
            [_table reloadData];
            [self.view addSubview:_table];
        }
        
    }else if (_segment.selectedSegmentIndex ==  1){
        CollectProgramaModel * collectModel = [CollectProgramaDatabase selectWithTitle:searchText];
        if(collectModel != nil){
            ArticleModel * model = [[ArticleModel alloc] init];
            model.id = collectModel.c_id;
            model.title = collectModel.c_title;
            
            // 组合simgs数组，里面只有一个元素，是一个字典，储存图片的尺寸和url
            NSMutableDictionary * simgsDic = [NSMutableDictionary dictionary];
            [simgsDic setValue:[NSNumber numberWithInteger:collectModel.c_height] forKey:@"height"];
            [simgsDic setValue:[NSNumber numberWithInteger:collectModel.c_width] forKey:@"width"];
            [simgsDic setValue:collectModel.c_url forKey:@"url"];
            NSArray * simgs = @[simgsDic];
            
            model.simgs = simgs;
            [self.collectionArray addObject:model];
            [model release];
            
            [_collection reloadData];
            [self.view addSubview:_collection]; // 保持在最上方
        }
        
    }
}
#pragma mark - 为查询到的新闻结果创建tableView
-(void)createTable{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + 50, self.view.frame.size.width, self.view.frame.size.height - 64 - 50) style:UITableViewStylePlain];
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    _table.backgroundColor = [UIColor clearColor];
    _table.delegate = self;
    _table.dataSource = self;
    [self.view addSubview:_table];
    [_table release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * defaultCellIdentify = @"defaultCell";
    NewsTableCell * cell = [tableView dequeueReusableCellWithIdentifier:defaultCellIdentify];
    if(!cell){
        cell = [[NewsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:defaultCellIdentify];
    }
    [cell sendMessageWithModel:[_tableArray objectAtIndex:indexPath.row]];
    
    // 搜索关键字高亮
    NSDictionary * dic = @{
                           NSBackgroundColorAttributeName : [UIColor yellowColor]};// 字体  字体颜色  背景颜色  删除线
    NSMutableAttributedString * attributeString = [cell.titleLabel.attributedText mutableCopy];
    NSRange range = [cell.titleLabel.text rangeOfString:_searchText]; // 得到搜索的字的位置
    [attributeString setAttributes:dic range:range];
    cell.titleLabel.attributedText = attributeString;
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kCellHeight;
}
// 当某一个cell被选中时，创建详情页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsTableCell * cell = (NewsTableCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    // 根据contentOffSet和indexPath判断cell在屏幕上的的位置
    CGFloat cellHeightInScreen = tableView.contentOffset.y - indexPath.row*kCellHeight;
    
    float scaleIniPhone6 = 377.0/667.0; // 以iPhone6的比例为标准计算当前的高度
    float originalImageHeight =  [UIScreen mainScreen].bounds.size.height*scaleIniPhone6;
    
    FashionNewsModel * model = [_tableArray objectAtIndex:indexPath.row];
    
    FashionDetailView * fashionDetail = [[FashionDetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) image:cell.originalImage imageRect:CGRectMake(0, -cellHeightInScreen, self.view.frame.size.width, originalImageHeight) model:model];
    [self.view addSubview:fashionDetail];
    [_searchBar resignFirstResponder];
}
#pragma mark tableView结束
#pragma mark -

#pragma mark - 为查询到的栏目结果创建collectionView
-(void)createCollection{
    SinglePullLayout * layout = [[[SinglePullLayout alloc] init] autorelease];
    layout.dicArr = _collectionArray; // 要内存相等！！！！！
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64 + 50, self.view.frame.size.width, self.view.frame.size.height - 64 - 50) collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor clearColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerClass:[DailyCollectionCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collection];
    [_collection release];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  _collectionArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DailyCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    ArticleModel * model = [_collectionArray objectAtIndex:indexPath.item];
    [cell setCellWithModel:model];
    
    // 搜索关键字高亮
    NSDictionary * dic = @{
                           NSBackgroundColorAttributeName : [UIColor yellowColor]};// 字体  字体颜色  背景颜色  删除线
    NSMutableAttributedString * attributeString = [cell.showImageView.label.attributedText mutableCopy];
    NSRange range = [cell.showImageView.label.text rangeOfString:_searchText]; // 得到搜索的字的位置
    [attributeString setAttributes:dic range:range];
    cell.showImageView.label.attributedText = attributeString;
    
    return cell;
}
// 进入详情
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ArticleModel * model = [_collectionArray objectAtIndex:indexPath.item];
    DailyDetailViewController * detail = [[DailyDetailViewController alloc] initWithModel:model];
    [self presentViewController:detail animated:YES completion:^{
        
    }];
}
#pragma mark collection创建完成
#pragma mark -
-(UIStatusBarStyle)preferredStatusBarStyle{
    return [NightMode nightModeON]?UIStatusBarStyleLightContent:UIStatusBarStyleDefault;
}
@end
